      PROGRAM FCSTBLD
C  THIS PROGRAM READS THE 1985 FORECAST EQUATION FILE AND GENERATES
C   FILES FOR ADDITIONAL YEARS.
C
C   BY JIM DOTY, DECEMBER 31, 1987
C
      CHARACTER ANS*1,STRING*10,CBTT*5,IST*2,IET*2
      CHARACTER LINE*80,CHYR*2,STA*5,FILE*28
      OPEN(UNIT=3,FILE='DRA2:[FORECAST]STATIONS.DAT',STATUS='OLD')
      WRITE(6,100)'$SHOULD I BUILD FILES FOR SELECTED FORECASTS?'
      READ(5,100)ANS
      WRITE(6,100)'$ENTER BEGINNING AND ENDING YEAR TO MAKE FILES FOR:'
      READ(5,*)ISTRT,IEND
      IF(ISTRT.GE.1900) ISTRT=ISTRT-1900
      IF(IEND.GE.1900) IEND=IEND-1900
C
      IF(ANS(1:1) .NE. 'Y')THEN
      WRITE(6,107)
107   FORMAT(' I WILL BUILD FILES FOR ALL OF THE STATIONS LISTED IN',
     +'THE STATIONS.DAT FILE',/) 
      GO TO 10
      ENDIF
C
      CBTT='     '
C     ENCODE(2,102,IST)ISTRT
C     ENCODE(2,102,IET)IEND
      OPEN(UNIT=4,FILE='DUA12:[FORECAST]STATIONS.SEL',STATUS='NEW',
     +CARRIAGECONTROL='LIST')
8     WRITE(6,100)'$ENTER CBTT CODE, XXXXX:'
      IWR=0
      READ(5,100)CBTT
      IF(CBTT(4:4) .EQ. ' ')CBTT(4:4)='_'
      IF(CBTT(5:5) .EQ. ' ')CBTT(5:5)='_'
9     READ(3,100,END=200)LINE
      IF(CBTT(1:2) .EQ. 'QU' .OR. CBTT(1:2) .EQ. 'EX')THEN
		REWIND 4
		REWIND 3
		GO TO 10
      ELSE IF(LINE(1:5) .EQ. CBTT)THEN
		WRITE(4,100)LINE
		IWR=IWR+1
		GO TO 9
      ENDIF
      GO TO 9
C
200   IF(IWR .EQ. 0)THEN
		WRITE(6,106)(LINE(N:N), N=1,5),CBTT
106   FORMAT(' COULD NOT FIND CBTT IN STATIONS.DAT ; LINE=',5A1,
     + ' CBTT=',A)
		REWIND 3
		GO TO 8
	ELSE IF(IWR .GT. 0)THEN
		REWIND 3
		GO TO 8
      ENDIF
C
10    DO 1 IY=ISTRT,IEND
      WRITE(CHYR,102) IY
  102 FORMAT(I2)
      OPEN(UNIT=2,FILE='EQUATE.'//CHYR,CARRIAGECONTROL='LIST',
     + STATUS='NEW')
      WRITE(2,105) IY
  105 FORMAT('FORECAST EQUATION',23X,'19',I2)
      REWIND 3
      REWIND 4
    7 IF(ANS(1:1) .NE. 'Y')READ(3,103,END=98) STA,IY1,IY2
      IF(ANS(1:1) .EQ. 'Y')READ(4,103,END=98) STA,IY1,IY2
  103 FORMAT(A5,2I2)
      IF(IY.LT.IY1.OR.IY.GT.IY2) GO TO 7
      WRITE(FILE,104) STA,IY1,IY2
  104 FORMAT('DRA2:[FORECAST]',A5,2I2,'.NEW')
      OPEN(UNIT=1,FILE=FILE,STATUS='OLD',ERR=97)
      GO TO 2
   97 WRITE(6,100) ' '//FILE//' NOT FOUND.'
      GO TO 7
    2 READ(1,100,END=99) LINE
  100 FORMAT(A)
      DO 4 I=80,1,-1
      IF(LINE(I:I).NE.' ') GO TO 3
    4 CONTINUE
      I=1
    3 LEN=I
      DO 5 I=1,LEN-3
      IF(LINE(I:I).EQ.'#') THEN
      WRITE(LINE(I:I+3),101) IY
  101 FORMAT('19',I2)
      ELSE IF(LINE(I:I).EQ.'@') THEN
      WRITE(LINE(I:I+3),101) IY-1
      END IF
    5 CONTINUE
      WRITE(2,100) LINE(1:LEN)
      GO TO 2
   99 CLOSE(UNIT=1,STATUS='KEEP')
      GO TO 7
   98 CLOSE(UNIT=2,STATUS='KEEP')
      GO TO 1
    1 CONTINUE
      CLOSE(UNIT=3,STATUS='KEEP')
      CLOSE(UNIT=4,STATUS='KEEP')
      STOP
      END
